package com.semanticbits.codejam.model

import ariba.appcore.*
import ariba.ui.meta.annotations.*
import ariba.ui.meta.annotations.Property.*
import ariba.ui.meta.persistence.*
import ariba.appcore.annotations.*
import org.compass.annotations.*
import javax.mail.internet.*;
import javax.mail.*
import javax.activation.*
import javax.persistence.*
import java.util.*
import groovy.text.SimpleTemplateEngine
import app.Application
import ariba.ui.meta.annotations.Trait.Required

/**
 * Created by IntelliJ IDEA.
 * User: carlos.perez
 * Date: 1/14/11
 * Time: 7:20 AM
 * To change this template use File | Settings | File Templates.
 */
@Entity @NavModuleClass @Searchable
@DefaultAccess @AnonymousAccess([Permission.ClassOperation.view])
class EmailTemplate {

    @Id @GeneratedValue @SearchableId
    private Long id

    @Required @SearchableProperty @Trait.LabelField
    String name

    String announcementSubject

    @Required @Trait.RichText
    String announcementTemplate

    String winnerSubject

    @Required @Trait.RichText
    String winnerTemplate



    String applyTemplate( String text, Contest contest )
    {
      def binding = ["contest":contest]
      def engine = new SimpleTemplateEngine()
      def template = engine.createTemplate(text).make(binding)

      return template.toString();
    }


    void saveMessage( Contest contest, String message, String prefix )
    {
         def subject = "ANN: New Code Jam ${contest.title}"
         def build_xml =
"""<?xml version="1.0"?>

<project name="Email Ant Task" default="mail" basedir=".">

<!--property file="../build.properties"/-->

<target name="mail">
<echo message="E-mailing!"/>
    <mail from="${Application.MAIL_FROM}"
          tolist="${Application.MAIL_TOLIST}"
          mailhost="${Application.MAIL_HOST}"
          mailport="${Application.MAIL_PORT}"
          ssl="${Application.MAIL_SSL}"
          user="${Application.MAIL_USER}"
          password="${Application.MAIL_PASSWORD}"
          subject="${subject}">
      <message><![CDATA[${message}]]>
      </message>
      <fileset dir="../content">
      </fileset>
    </mail>
</target>
</project>
"""
          new File("${app.Application.SHARED_DIR}/${contest.jobName}").mkdir();

          def file = new File( "${app.Application.SHARED_DIR}/${contest.jobName}/build.xml" )
          PrintWriter pw = new PrintWriter(file)
          pw.write(build_xml.toString())
          pw.close()
    }



}
